package com.cy.login.comment.exection;

import com.cy.login.comment.core.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public ResponseResult<?> serviceException(ServiceException e) {
        String message = e.getMessage();
        log.error("异常已捕获");
        e.printStackTrace();
        return ResponseResult.error(message);
    }
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public ResponseResult<?> MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(";"));
        log.error("异常已捕获");
        e.printStackTrace();
        return ResponseResult.error("请求参数错误: "+message);
    }
    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseBody
    public ResponseResult<?> ConstraintViolationException(ConstraintViolationException e) {
        String message = e.getMessage().split(":")[1];
        log.error("异常已捕获");
        e.printStackTrace();
        return ResponseResult.error("请求参数错误: "+message);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult<?> exception(Exception e) {
        log.error("异常已捕获");
        e.printStackTrace();
        return ResponseResult.error("服务器异常");
    }
}
